const { API_OK } = require('../../utils/setting')
const { category, goodsList, bannerList, wxRequest } = require('../../api/goods')
const app =  getApp()

Page({
  data: {
    loading: false,
    userInfo: null,
    keyword: '',
    sortLabels: [
      { label: '综合', value: 'all', sort: false },
      { label: '销量', value: 'sales', sort: true, status: 0 },
      { label: '新品', value: 'new', sort: true, status: 0 },
      { label: '价格', value: 'price', sort: true, status: 0 }
    ],
    activeSortIndex: 0,
    tabs: [],
    categoryId: 0,
    goods: [],
    cartNumber: 0
  },
  pageData: {
    page: 1,
    canLoadMore: true
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function () {
    if (app.globalData.userInfo) {
      this.setData({ userInfo: app.globalData.userInfo })
    } else {
      app.userInfoReadyCallback = res => {
        this.setData({ userInfo: res.userInfo })
      }
    }
    if (wx.getStorageSync('token')) {
      this.getCartNumber()
    } else {
      app.tokenReadyCallback = this.getCartNumber
    }
    this.setData({ loading: true })
    wx.showLoading({ title: '拼命加载中' })
    await this.getTabs()
    this.getCreditGoods()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onPullDownRefresh: async function () {
    Object.keys(wxRequest.queue).forEach(task => {
      wxRequest.queue[task].abort()
    })
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({ loading: true, goods: [], tabs: [] })
    wx.showLoading({ title: '拼命加载中' })
    await this.getTabs()
    this.getCreditGoods()
  },
  onReachBottom() {
    if (!this.pageData.canLoadMore) return
    this.pageData.page += 1
    this.setData({ loading: true })
    this.getCreditGoods()
  },
  /**
   * 重置查询课程的搜索条件
   */
  resetConditions() {
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({
      sortLabels: [
        { label: '综合', value: 'all', sort: false },
        { label: '销量', value: 'sales', sort: true, status: 0 },
        { label: '新品', value: 'new', sort: true, status: 0 },
        { label: '价格', value: 'price', sort: true, status: 0 }
      ],
      activeSortIndex: null,
      categoryId: 0
    })
  },
  /**
   * 修改搜索关键字
   */
  changeKeyword({detail: {value}}) {
    this.setData({ keyword: value })
  },
   /**
   * 搜索课程
   */
  search() {
    this.resetConditions()
    this.setData({ loading: true, goods: [] })
    this.getCreditGoods()
  },
  /**
   * 切换商品分类
   */
  changeTabIndex({detail: {name}}) {
    // console.log(name)
    this.setData({ categoryId: name, loading: true, goods: [] })
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.getCreditGoods()
  },
  /**
   * 修改选中的排序
   */
  changeActiveIndex({ detail }) {
    if (this.data.activeSortIndex === detail.index) return
    const lastIndexLabel = this.data.sortLabels[this.data.activeSortIndex]
    lastIndexLabel.sort && (lastIndexLabel.status = 0)
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({
      activeSortIndex: detail.index,
      sortLabels: this.data.sortLabels,
      loading: true,
      goods: []
    }, () => { this.getCreditGoods() })
  },
  /**
   * 修改排序规则（升降序）
   */
  changeSortStatus({detail}) {
    const target = this.data.sortLabels[detail.index]
    target.status = target.status === 0 ? 1 : 0
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({
      sortLabels: this.data.sortLabels,
      loading: true,
      goods: []
    }, () => { this.getCreditGoods() })
  },
  /**
   * 获取商品分类
   */
  async getTabs() {
    try {
      const res = await category({ data: { type: 2 }, callback: wx.hideLoading })
      // console.log(res)
      if (res.code === API_OK) {
        const tabs = res.data.list.map(tab => ({ id: tab.category_id, label: tab.name })) || []
        tabs.unshift({id: 0, label: '全部商品'})
        const currentTab = tabs.filter(item => item.id === this.data.categoryId)
        const categoryId = currentTab.length ? this.data.categoryId : 0
        this.setData({ tabs, categoryId })
      }
    } catch(err) { console.warn(err) }
  },
  /**
   * 获取商品列表
   */
  async getCreditGoods() {
    try {
      const res = await goodsList({
        data: {
          type: 2,
          category_id: this.data.categoryId,
          keywords: this.data.keyword,
          is_total: 0,
          is_sales: this.data.sortLabels[1].status,
          is_new: this.data.sortLabels[2].status,
          is_price: this.data.sortLabels[3].status,
          p: this.pageData.page
        },
        callback: wx.stopPullDownRefresh
      })
      if (res.code === API_OK) {
        // console.log(res)
        this.pageData.canLoadMore = res.data.list.current_page < res.data.list.last_page
        this.setData({
          loading: false,
          goods: res.data.list.data.map(goods => {
            return {
              id: goods.goods_id,
              image: (goods.image && goods.image.length) ? goods.image[0].file_path : '',
              name: goods.goods_name,
              price: goods.goods_price,
              credit: goods.score_deduct * 1
            }
          })
        })
      }
    } catch (err) {
      console.warn(err)
      wx.stopPullDownRefresh()
      this.setData({ loading: false })
    }
  },
  getCartNumber() {}
})
